package br.ufpb.di.knowledgetv.sqtv.utils;

import java.io.File;

import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.tdb.TDBFactory;
import org.apache.jena.query.text.TextDatasetFactory;

public class RDFDatabase {
	private Dataset dataset;
	public static String DB_PATH = "databases/rdfs";
	private static RDFDatabase instance = new RDFDatabase();
	
	private RDFDatabase() {
        try {
            File f = new File(RDFDatabase.DB_PATH);
            if (!f.exists()) {
                f.mkdirs();
            }
            //this.dataset = DatasetFactory.assemble(getClass().getResource("/assemblers/text-search-config.ttl").getPath(), "http://localhost/jena_example/#text_dataset");
            this.dataset = TDBFactory.createDataset(RDFDatabase.DB_PATH);
            //this.dataset = TextDatasetFactory.create(getClass().getResource("/assemblers/text-search-config.ttl").getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	public void saveModel(Model model) {
		this.dataset.begin(ReadWrite.WRITE);
		try {
			Model defaultModel = dataset.getDefaultModel();
			defaultModel.add(model);
			dataset.commit();
		} finally {
			dataset.end();
		}
	}
	
	public ResultSet searchBySparql(String sparql) {
		ResultSet result;
		try {
			this.dataset.begin(ReadWrite.READ);
			QueryExecution qExec = QueryExecutionFactory.create(sparql, this.dataset);
			result = qExec.execSelect();
		} finally {
			dataset.end();
		}
		return result;
		
	}

	public static RDFDatabase getInstance() {
		return instance;
	}

	public Dataset getDataset() {
		return dataset;
	}

	public Model getDefaultModel() {
		return this.dataset.getDefaultModel();
	}
	
}
